# $Id: unzip.tcl 7 2007-06-17 15:05:31Z khomoutov $
# Provides wrapper around different zlib implementations
# available for Tcl.
# They are tried in this order:
# 1. "zlib" package:
#   a) May pick up either the "critlib" implementation
#      (which is found in tclkits and is also available
#      from Pascal Scheffers as a standalone extension)
#      or "ztcl" package from Marco Maggi.
# 2. "Trf" package. Makes the "zip" command available,
#    if such support is compiled in.
# TODO provide pure-Tcl zlib decompressor, if available.

namespace eval ::tclplkr {}

# Name:
#  Zlib_init
# Purpose:
#  Try to find a working implementation of zlib
#  decompressor.
# Returns:
#  True if the decompressor was found and initialized,
#  false otherwise.
# Side effects:
#  Creates a command named "zlib" in the global namespace
#  which is guaranteed to support at least one subcommand
#  named "decompress" which takes raw compressed binary
#  data and returns decompressed data, as in:
#  set orig [::zlib decompress $compressed]
proc ::tclplkr::Zlib_init {} {
	expr {
		[Zlib_have_zlib_pkg] \
		|| [Zlib_have_trf_pkg]
	}
}

proc ::tclplkr::Zlib_have_zlib_pkg {} {
	if {[catch {package require zlib}]} {
		return false
	}
	
	if {[catch {string equal \
		[zlib decompress [zlib compress test]] \
		test
	} res]} {
		return false
	} else {
		return $res
	}
}

proc ::tclplkr::Zlib_have_trf_pkg {} {
	if {[catch {package require Trf}]} {
		return false
	}

	if {[catch {string equal \
		[zip -mode decompress [zip -mode compress test]] \
		test
	} test_ok]} {
		return false
	} elseif {$test_ok} {
		interp alias {} ::zlib {} ::zip -mode
		return true
	}
}

